package service

import (
	"log"
	"ozonTest/internal/domain/comments/dao"
	"ozonTest/internal/domain/comments/model"
)

type CommentsService interface {
	AddComment(comment *model.Comment) error
	AddReply(parentID int, reply *model.Comment) error
	GetCommentByID(id int) (*model.Comment, error)
	GetAllComments() ([]model.Comment, error)
	DeleteCommentByID(id int) error
	GetAllPostComments(postID int) ([]*model.Comment, error)
}

type commentsService struct {
	repo dao.CommentsDAO
}

func NewCommentsService(repo dao.CommentsDAO) CommentsService {
	return &commentsService{repo: repo}
}

func (s *commentsService) AddComment(comment *model.Comment) error {
	err := s.repo.CreateComment(comment)
	if err != nil {
		log.Printf("Error adding comment: %v", err)
		return err
	}

	log.Printf("Comment added: %+v", comment)
	return nil
}

func (s *commentsService) AddReply(parentID int, reply *model.Comment) error {
	err := s.repo.CreateReply(parentID, reply)
	if err != nil {
		log.Printf("Error adding reply: %v", err)
		return err
	}

	log.Printf("Reply added: %+v", reply)
	return nil
}

func (s *commentsService) GetCommentByID(id int) (*model.Comment, error) {
	comment, err := s.repo.GetComment(id)
	if err != nil {
		log.Printf("Error retrieving comment by ID %d: %v", id, err)
		return nil, err
	}

	log.Printf("Comment retrieved: %+v", comment)
	return comment, nil
}

func (s *commentsService) GetAllComments() ([]model.Comment, error) {
	comments, err := s.repo.GetAllComments()
	if err != nil {
		log.Printf("Error retrieving all comments: %v", err)
		return nil, err
	}

	log.Printf("All comments retrieved: %+v", comments)
	return comments, nil
}

func (s *commentsService) DeleteCommentByID(id int) error {
	err := s.repo.DeleteComment(id)
	if err != nil {
		log.Printf("Error deleting comment by ID %d: %v", id, err)
		return err
	}

	log.Printf("Comment deleted: ID %d", id)
	return nil
}

func (s *commentsService) GetAllPostComments(postID int) ([]*model.Comment, error) {
	comments, err := s.repo.GetCommentsByPost(postID)
	if err != nil {
		log.Printf("Error retrieving comments for post ID %d: %v", postID, err)
		return nil, err
	}

	log.Printf("Comments retrieved for post ID %d: %+v", postID, comments)
	return comments, nil
}
